package com.qianxx.base.utils;

import android.content.Context;
import android.content.SharedPreferences;

/**
 * 基础参数的操作
 */
public class SPUtil {

	private static final String DBName = "qianxx"; // 基础参数放置的数据库名称
	private static Context mContext;
	private static SPUtil instance;
	private SharedPreferences sp;

	public static void initContext(Context mContext) {
		SPUtil.mContext = mContext;
	}

	private SPUtil() {
	}

	public static SPUtil getInstance() {
		if (instance == null) {
			synchronized (SPUtil.class) {
				if (instance == null) {
					instance = new SPUtil();
				}
			}
		}
		return instance;
	}

	private void findSP() {
		if (sp == null) {
			sp = mContext.getSharedPreferences(DBName, Context.MODE_PRIVATE);
		}
	}

	// 获取SP的实例
	public SharedPreferences getSP() {
		findSP();
		return sp;
	}
	

	/**
	 * 获取登录token
	 */
	public String getToken() {
		findSP();
		return sp.getString("token", "");
	}

	/**
	 * 设置登录token
	 */
	public void setToken(String token) {
		findSP();
		SharedPreferences.Editor editor = sp.edit();
		editor.putString("token", token);
		editor.commit();
	}

	/**
	 * 获取登录用户id
	 */
	public String getUserId() {
		findSP();
		return sp.getString("UserId", "");
	}

	/**
	 * 设置登录用户id
	 */
	public void setUserId(String userId) {
		findSP();
		SharedPreferences.Editor editor = sp.edit();
		editor.putString("UserId", userId);
		editor.commit();
	}
	/**
	 * 清空token
	 */
	public void clearToken() {
		setToken("");
	}

	/**
	 * 是否为首次打开应用
	 */
	public boolean isFirst() {
		findSP();
		return sp.getBoolean("isFirst", true);
	}

	/**
	 * 设置"是否为首次打开应用"；
	 * 
	 * 调用时，一般设置false
	 */
	public void setFirst(boolean isFirst) {
		findSP();
		SharedPreferences.Editor editor = sp.edit();
		editor.putBoolean("isFirst", isFirst);
		editor.commit();
	}

	/**
	 * 登录的类型
	 */
	public String getType() {
		findSP();
		return sp.getString("type", "");
	}

	/**
	 * 设置登录的类型
	 */
	public void setType(String type) {
		findSP();
		SharedPreferences.Editor editor = sp.edit();
		editor.putString("type", type);
		editor.commit();
	}

	/**
	 * GET openId
	 * @return
	 */
	public String getOpenId() {
		findSP();
		return sp.getString("openId", "");
	}

	/**
	 * 设置 openId
	 */
	public void setOpenId(String openId) {
		findSP();
		SharedPreferences.Editor editor = sp.edit();
		editor.putString("openId", openId);
		editor.commit();
	}

	/**
	 * 得到年龄
	 * @return
	 */
	public String getAge() {
		findSP();
		return sp.getString("age", "");
	}

	/**
	 * 设置年龄
	 */
	public void setAge(String age) {
		findSP();
		SharedPreferences.Editor editor = sp.edit();
		editor.putString("age", age);
		editor.commit();
	}

	/**
	 * 得到年龄
	 * @return
	 */
	public String getLongAge() {
		findSP();
		return sp.getString("longage", "");
	}

	/**
	 * 设置年龄
	 */
	public void setLongAge(String longage) {
		findSP();
		SharedPreferences.Editor editor = sp.edit();
		editor.putString("longage", longage);
		editor.commit();
	}

}
